﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Web.Script.Services;
using PhoneDBModel;
using System.Linq.Expressions;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (SessionHandler.AuthUser == null)
        {
            Response.Redirect("Login.aspx");
        }
        dlContacts.InnerHtml = LoadContacts(false);
        ClientScript.RegisterClientScriptBlock(this.GetType(), "varName", "var myChatName = '" + SessionHandler.AuthUser.UserName + "';", true);

        lblCredit.Text = LoadUserCredit();
    }

    [WebMethod]
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
    public static string LoadContacts(bool returnJson)
    {
        string htmlresult = string.Empty;
        PhoneDBEntities dbe = new PhoneDBEntities();
        Expression<Func<Contact, object>> orderByFunction;
        if (returnJson == true)
        {
            orderByFunction = c => c.Id;
        }
        else
        {
            orderByFunction = c => c.Name;
        }

        var contacts = dbe.Contacts.Where(c => c.OwnerId == SessionHandler.AuthUser.Id || c.UserId == SessionHandler.AuthUser.Id).OrderBy(c =>c.Name);
        foreach (Contact c in contacts)
        {
            if (c.UserId != null && c.OwnerId == SessionHandler.AuthUser.Id)
            {
                c.User1Reference.Load();
                c.Name = c.User1.UserName;
                c.Email = c.User1.Email;
                c.Phone = c.User1.Phone;
            }
            else if (c.OwnerId != SessionHandler.AuthUser.Id)
            {
                c.UserReference.Load();
                c.Name = c.User.UserName;
                c.Email = c.User.Email;
                c.Phone = c.User.Phone;
            }

            htmlresult += "<dt>" + c.Name + "</dt>";
            htmlresult += "<dd>" + c.Phone + "<br />" + c.Email + "<br />";
            htmlresult += "<img src=\"/Styles/Images/phone-icon.png\" onclick=\"$('#phoneNumber').val('" + c.Phone + "');onClick();\" />";
            if (c.UserId != null)
            {
                htmlresult += "<img src=\"/Styles/Images/chat.png\" onclick=\"getChatWindow('" + c.Name + "');\" />";
            }

            htmlresult += "<img src=\"/Styles/Images/delete-icon.png\" onclick=\"deleteContact(" + c.Id + ");\" />";
            htmlresult += "</dd>";
        }
        if (returnJson)
        {
            htmlresult = "{\"Response\":\"" + htmlresult.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"}";
        }
        return htmlresult;
    }

    [WebMethod]
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
    public static string RequestCall(string phoneNumber)
    {
        string country = CheckPhoneNumber.GetCountry(phoneNumber);
        int[] isOk = CheckPhoneNumber.IsOkNumber(phoneNumber);

        if (isOk[0] == 1)
        {
            PhoneDBEntities dbe = new PhoneDBEntities();
            AccountBalance ab = dbe.AccountBalances.Where(x => x.Userid == SessionHandler.AuthUser.Id).FirstOrDefault();
            decimal credit = 0;
            if (ab != null)
            {
                credit = ab.Credit;
            }

            Price p = dbe.Prices.Where(x => x.Code == country).FirstOrDefault();

            CallRequest cr = new CallRequest();
            cr.Code = Guid.NewGuid().ToString("N");
            cr.MaxDuration = (int)Math.Truncate((decimal)(credit/p.CPM)/60);
            cr.Phone = phoneNumber;
            cr.Timestamp = DateTime.Now;
            cr.UserId = SessionHandler.AuthUser.Id;

            dbe.CallRequests.AddObject(cr);
            dbe.SaveChanges();
            return "{\"Code\":\"" + "200" + "\", \"ext\":\"" + cr.Code + "\", \"peer\":\"" + Guid.NewGuid().ToString("N") + "\"}";
        }
        else
        {
            return "{\"Code\":\"" + "403" + "\", \"Message\":\"Numarul de telefon introdus nu este valid\"}";
        }

        //{"Code":"200", "ext":"1c1b55ff21db4b379a5495ff1c005a9e", "peer":"1a649b3fb8714531a73c4f430e4cca59"}

    }

    [WebMethod]
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
    public static void DeleteContact(int id)
    {
        PhoneDBEntities dbe = new PhoneDBEntities();
        var contact = dbe.Contacts.Where(c => c.Id == id && (c.UserId == SessionHandler.AuthUser.Id || c.OwnerId == SessionHandler.AuthUser.Id)).First();
        dbe.Contacts.DeleteObject(contact);
        dbe.SaveChanges();
    }

    [WebMethod]
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
    public static string LoadUserCredit()
    {
        PhoneDBEntities dbe = new PhoneDBEntities();
        AccountBalance ab = dbe.AccountBalances.Where(x => x.Userid == SessionHandler.AuthUser.Id).FirstOrDefault();
        if (ab != null)
        {
            return ab.Credit.ToString();
        }

        return string.Empty;
    }
}
